package com.streaminggbs.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

@Configuration
@Slf4j
@MapperScan(basePackages = WriteDataSourcesConfig.PACKAGES,sqlSessionFactoryRef = "writeSqlSessionFactory")
public class WriteDataSourcesConfig {

    static final String PACKAGES="com.streaminggbs.mapper.write";
    private  static final String MAPPER_LOCAL ="classpath:mapper/write/*.xml";

    /** 配置写库
     * @return  DruidDataSource
     */
    @Bean(name = "writeDataSource")
    @Primary
    @ConfigurationProperties(prefix = "write.datasource")
    public DruidDataSource writeDruidDataSource(){
        return new DruidDataSource();
    }


    @Bean(name = "writeSqlSessionFactory")
    @Primary
    public SqlSessionFactory writeSqlSessionFactory(){
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(writeDruidDataSource());

        try {
            sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCAL));
            return sessionFactoryBean.getObject();
        } catch (Exception e) {
            log.error("配置写库的SqlSessionFactory失败，error:{}",e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    @Bean(name = "writeTransactionManager")
    @Primary
    public DataSourceTransactionManager writeTransactionManager(){
        return new DataSourceTransactionManager(writeDruidDataSource());
    }

}
